package cn.ekuma.odbo.mobile.ui

import com.openbravo.data.user.DirtyListener
import java.util.*

abstract class AbstractEditorRecordHolder<T>:EditorRecordHolder<T> {

    protected var dirtyState:Boolean=false

    protected var listener: DirtyListener?=null
    protected var currentState:EditorRecordState=EditorRecordState.EOF
    var currentItem:T?=null

    protected var stateChangeListener:EditorRecordStateChangeListener?=null

    abstract fun createNewItem(prop: Properties?):T

    override fun setDirtyListener(l: DirtyListener?) {
        listener=l
    }

    override fun isLogAble(): Boolean =false

    override fun getLogerString(): String =""

    override fun activate() {
        refresh()
    }

    override fun writeValueEdit(value: T) {
        currentItem=value
        setToEditorState(EditorRecordState.EDIT)
        refresh()
    }

    override fun refresh() {
        refresh(currentItem)
        setDirty(false)
    }

    override fun writeValueInsert(prop: Properties?) {
        writeValueInsert(createNewItem(prop))
    }

    override fun writeValueEOF() {
        currentItem=null
        setToEditorState(EditorRecordState.EOF)
        refresh()
    }

    override fun writeValueDelete(value: T?) {
        currentItem=value
        setToEditorState(EditorRecordState.DELETE)
        refresh()
    }

    override fun writeValueInsert(item:T) {
        currentItem=item
        setToEditorState(EditorRecordState.INSERT)
        refresh()
    }


    fun setDirty(dirty:Boolean){
        if(this.dirtyState!=dirty){
            this.dirtyState=dirty
            fireDirtyStateChanged(dirty)
        }
    }

    fun editAble():Boolean=currentState in editStates



    override fun setEditorRecordStateChangeListener(listener: EditorRecordStateChangeListener?) {
        stateChangeListener=listener
    }

    private fun setToEditorState(toState: EditorRecordState){
        if(currentState!=toState){
            val fromState=currentState
            currentState=toState
            fireEditorStateChanged(fromState,toState)
        }
    }

    protected fun fireEditorStateChanged(from:EditorRecordState,to: EditorRecordState){
        stateChangeListener?.editorRecordStateChange(from,to)
    }

    protected fun fireDirtyStateChanged(dirty:Boolean){
        listener?.changedDirty(dirty)
    }

    override fun currentState(): EditorRecordState=currentState

    companion object State{
        val editStates=listOf(EditorRecordState.EDIT,EditorRecordState.INSERT)
    }
}